package model

import "github.com/jinzhu/gorm"

type Article struct {
	*Model
	Title     string `json:"title"`
	CoverUrl  string `json:"cover_url"`
	Introduce string `json:"introduce"`
	Content   string `json:"content"`

	AuthorId uint32 `json:"author_id"`
}

type ArticleDetail struct {
	ID         int    `json:"id"`
	CreatedOn  int    `json:"created_on"`
	Title      string `json:"title"`
	CoverUrl   string `json:"cover_url"`
	Introduce  string `json:"introduce"`
	Content    string `json:"content"`
	AuthorName string `json:"author_name"`
}

type ArticlePart struct {
	ID        int    `json:"id"`
	CreatedOn int    `json:"created_on"`
	Title     string `json:"title"`
	CoverUrl  string `json:"cover_url"`
	Introduce string `json:"introduce"`

	NickName string `json:"nick_name"`
}

func (a Article) TableName() string {
	return "article"
}

func (a Article) All(db *gorm.DB, pageOffset, pageSize int) ([]*ArticlePart, error) {
	var articles []*ArticlePart
	var err error

	// 判断是否需要分页
	if pageSize > 0 && pageOffset >= 0 {
		db = db.Offset(pageOffset).Limit(pageSize)
	}
	err = db.Table("article").Where("article.is_del = ?", 0).
		Select("article.id, article.created_on, article.title, article.cover_url," +
			" article.introduce, user.nick_name").
		Joins("join user on article.author_id = user.id").Scan(&articles).Error

	return articles, err
}

func (a Article) Create(db *gorm.DB) error {
	return db.Create(&a).Error
}

func (a Article) GetDetail(db *gorm.DB) (*ArticleDetail, error) {
	var details = &ArticleDetail{}
	var err error

	err = db.Table("article").
		Where("article.id = ? AND article.is_del = ?", a.ID, 0).
		Select("article.id, article.title, article.cover_url, article.created_on," +
			"article.introduce, article.content, user.name AS author_name").
		Joins("join user on article.author_id = user.id").First(&details).Error

	if err != nil {
		panic(err.Error())
	}

	return details, err
}
